package com.git.smp.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.HistoricFormPropertyEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.git.smp.core.PageRequest;
import com.git.smp.core.ResponseMessage;
import com.git.smp.dao.RequireApplyMapper;
import com.git.smp.dao.RequirementBatchMapper;
import com.git.smp.dao.RequirementBatchTiemMapper;
import com.git.smp.dao.SmpUserRoleMapper;
import com.git.smp.entity.Examine;
import com.git.smp.entity.RequireApply;
import com.git.smp.entity.RequirementBatch;
import com.git.smp.entity.RequirementBatchKey;
import com.git.smp.entity.RequirementBatchTiem;
import com.git.smp.entity.SmpUser;
import com.git.smp.utils.Constants;
import com.git.smp.websocket.TaskServer;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/process")
public class ActivitiController {

	Logger logger = LoggerFactory.getLogger(ActivitiController.class);

	@Resource
	RuntimeService runtimeService;

	@Resource
	TaskService taskService;

	@Resource
	HistoryService historyService;

	@Resource
	RepositoryService repositoryService;

	@Autowired
	ProcessEngineConfiguration engineConfiguration;

	@Autowired
	FormService formService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	RequireApplyMapper applyMapper;

	@Autowired
	RequireApplyMapper requireApplyMapper;

	@Autowired
	RequirementBatchMapper requirementBatchMapper;

	@Autowired
	RequirementBatchTiemMapper requirementBatchTiemMapper;

	@Value("${developRoleId}")
	private String developRoleId;

	@Autowired
	SmpUserRoleMapper smpUserRoleMapper;

	@Autowired
	TaskServer taskServer;

	@RequestMapping("/hello")
	public String hello() {
		PageHelper.startPage(1, 10);
		// List<RequireApply> lists = applyMapper.selectAll();
		// PageInfo<RequireApply> pageInfo = new PageInfo<RequireApply>(lists);
		return "hello";
	}

	/**
	 * 工单申请
	 * 
	 * @return
	 */
	@RequestMapping("/create")
	public ResponseMessage<?> create(@RequestBody RequireApply requireApply) {

		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("工单提交成功成功！");
		String applyUser = request.getHeader("userName");

		Map param = new HashMap<>();
		param.put("applyUser", applyUser);
		// formService.
		ProcessInstance instance = runtimeService.startProcessInstanceByKey("MyProcess", param);
		// ProcessInstance instance = formService.submitStartFormData("MyProcess",
		// param);

		// formService.submitStartFormData(instance.getProcessInstanceId(), param);
		// StartFormData startFormData = formService.getStartFormData(instance.getId());
		// instance.
		// logger.info(instance.getProcessVariables().toString());

		Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).singleResult();

		// 通过角色获取服务管理员
		Map formData = new HashMap();
		formData.put("applyDate", new Date());
		formData.put("adminUser", "huangjie");
		logger.info("提交表单数据");
		// formService.submitTaskFormData(task.getId(), formData);

		// logger.info("表单数据提交成功");
		// 提交工单申请
		taskService.complete(task.getId(), formData);
		return responseMessage;
	}

	/**
	 * 需求保存
	 * 
	 * @return
	 */
	@RequestMapping("/save")
	public String save() {
		Map param = new HashMap();
		param.put("userId", "10001");
		ProcessInstance instance = runtimeService.startProcessInstanceByKey("MyProcess", param);
		// StartFormData startFormData = formService.getStartFormData(instance.getId());
		/*
		 * Task task = taskService.createTaskQuery().processInstanceId(instance.getId())
		 * .taskDefinitionKey("demandApplication").singleResult();
		 * 
		 * Map formData = new HashMap(); formData.put("userName", "张三");
		 * logger.info("提交表单数据"); formService.submitTaskFormData(task.getId(),
		 * formData); logger.info("表单数据提交成功");
		 */
		// taskService.complete(task.getId());

		return "流程编号" + instance.getId();
	}

	/**
	 * 需求审批
	 * 
	 * @return
	 */
	@RequestMapping("/verifyTask")
	public ResponseMessage<?> verifyTask(@RequestParam String taskId) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("审批成功");
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		if (task == null) {
			responseMessage.setCode("0001");
			responseMessage.setMessage("任务不存在或已被其他用户执行");
		}
		return responseMessage;
	}

	/**
	 * 需求审批
	 * 
	 * @return
	 */
	@RequestMapping("/examine")
	public ResponseMessage<?> examine(@RequestBody Examine examine) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("审批成功");
		Map formData = new HashMap();
		if ("2".equals(examine.getStatus())) {
			formData.put("developmentUserId", examine.getDevelopmentUserId());
		} else if ("5".equals(examine.getStatus())) {// 转派
			// formData.put("developmentUserId", examine.getDevelopmentUserId());
			// formData.put("developmentUserId", examine.getDevelopmentUserId());
			// 获取开发人员列表
			List<String> developList = smpUserRoleMapper.selectByRoleId(developRoleId);
			formData.put("developUsers", developList);
		}

		formData.put("status", examine.getStatus());

		Map localVar = new HashMap();
		localVar.put("status", examine.getStatus());
		localVar.put("resultMessage", examine.getResultMessage());

		Task task = taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		String dealUser = request.getHeader("userName");

		taskService.setVariablesLocal(examine.getTaskId(), localVar);

		taskService.claim(examine.getTaskId(), dealUser);

		taskService.complete(examine.getTaskId(), formData);

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					taskServer.SendMessage(task.getProcessInstanceId());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();

		/*
		 * task =
		 * taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).
		 * singleResult(); // task.ca List<IdentityLink> identityLinks =
		 * taskService.getIdentityLinksForTask(task.getId()); for (IdentityLink
		 * identityLink : identityLinks) { String UserId = identityLink.getUserId();
		 * logger.info("用户Id" + UserId); }
		 */

		// formService.submitTaskFormData(taskId, formData);

		/*
		 * ProcessInstance instance = runtimeService.createProcessInstanceQuery()
		 * .processInstanceId(task.getProcessInstanceId()).singleResult();
		 */

		// 变更工单状态
		RequireApply requireApply = new RequireApply();

		requireApply.setId(examine.getApplyId());
		requireApply.setStatus(examine.getStatus());

		requireApplyMapper.updateStatusByID(requireApply);

		return responseMessage;
	}

	/**
	 * 开发拒绝
	 * 
	 * @return
	 */
	@RequestMapping("/developmentReject")
	public ResponseMessage<?> developmentReject(@RequestBody Examine examine) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("审批成功");
		Map formData = new HashMap();

		formData.put("status", "9");

		Map localVar = new HashMap();
		localVar.put("status", "9");
		localVar.put("resultMessage", examine.getResultMessage());

		Task task = taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		String dealUser = request.getHeader("userName");

		taskService.setVariablesLocal(examine.getTaskId(), localVar);

		taskService.claim(examine.getTaskId(), dealUser);

		taskService.complete(examine.getTaskId(), formData);
		/*
		 * task =
		 * taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).
		 * singleResult(); // task.ca List<IdentityLink> identityLinks =
		 * taskService.getIdentityLinksForTask(task.getId()); for (IdentityLink
		 * identityLink : identityLinks) { String UserId = identityLink.getUserId();
		 * logger.info("用户Id" + UserId); }
		 */

		// formService.submitTaskFormData(taskId, formData);

		/*
		 * ProcessInstance instance = runtimeService.createProcessInstanceQuery()
		 * .processInstanceId(task.getProcessInstanceId()).singleResult();
		 */

		// 变更工单状态
		RequireApply requireApply = new RequireApply();
		requireApply.setId(examine.getApplyId());
		requireApply.setStatus("9");
		requireApplyMapper.updateStatusByID(requireApply);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					taskServer.SendMessage(task.getProcessInstanceId());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		return responseMessage;
	}

	/**
	 * 需求转派
	 * 
	 * @return
	 */
	@RequestMapping("/acceptReassignment")
	public ResponseMessage<?> acceptReassignment(@RequestBody Examine examine) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("转派成功");
		Map formData = new HashMap();
		formData.put("status", "5");// 转派

		String oldDevelopmentUserId = request.getHeader("userName");
		formData.put("newDevelopmentUserId", examine.getDevelopmentUserId());// 新开发人员
		formData.put("resultMessage", examine.getResultMessage());// 转派理由

		Map localVar = new HashMap();
		localVar.put("status", "5");
		localVar.put("resultMessage", examine.getResultMessage());

		Task task = taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		taskService.setVariablesLocal(examine.getTaskId(), localVar);

		taskService.complete(examine.getTaskId(), formData);

		// formService.submitTaskFormData(taskId, formData);

		/*
		 * ProcessInstance instance = runtimeService.createProcessInstanceQuery()
		 * .processInstanceId(task.getProcessInstanceId()).singleResult();
		 */

		// 变更工单状态
		RequireApply requireApply = new RequireApply();

		requireApply.setId(examine.getApplyId());
		requireApply.setStatus("5");

		requireApplyMapper.updateStatusByID(requireApply);

		/*
		 * task =
		 * taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).
		 * singleResult(); // task.ca List<IdentityLink> identityLinks =
		 * taskService.getIdentityLinksForTask(task.getId()); for (IdentityLink
		 * identityLink : identityLinks) { String UserId = identityLink.getUserId();
		 * logger.info("用户Id" + UserId); }
		 */

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					taskServer.SendMessage(task.getProcessInstanceId());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
		return responseMessage;
	}

	/**
	 * 需求受理
	 * 
	 * @return
	 */
	@RequestMapping("/acceptDemand")
	public ResponseMessage<?> acceptDemand(@RequestBody Examine examine) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("受理成功");
		Map formData = new HashMap();
		formData.put("status", "4");// 受理

		Map localVar = new HashMap();
		localVar.put("status", "4");
		localVar.put("resultMessage", examine.getResultMessage());

		Task task = taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		// taskService.setVariablesLocal(examine.getTaskId(), localVar);

		String dealUser = request.getHeader("userName");

		taskService.setVariablesLocal(examine.getTaskId(), localVar);

		taskService.claim(examine.getTaskId(), dealUser);

		formData.put("developmentUserId", dealUser);

		taskService.complete(examine.getTaskId(), formData);

		// formService.submitTaskFormData(taskId, formData);

		/*
		 * ProcessInstance instance = runtimeService.createProcessInstanceQuery()
		 * .processInstanceId(task.getProcessInstanceId()).singleResult();
		 */

		// 变更工单状态
		RequireApply requireApply = new RequireApply();

		requireApply.setId(examine.getApplyId());
		requireApply.setStatus("4");

		requireApplyMapper.updateStatusByID(requireApply);

		// 判断需求批次表 REQUIREMENT_BATCH 有就修改，没有就添加
		Date applyDate = new Date();
		String applyUser = request.getHeader("userName");

		RequireApply requireApply2 = requireApplyMapper.selectByPrimaryKey(examine.getApplyId());

		if (!Constants.APPLY_TYPE_04.equals(requireApply2.getApplyType())) {
			RequirementBatch requirementBatch = new RequirementBatch();
			requirementBatch.setQmsNo(requireApply2.getQmsNo());
			requirementBatch.setBatchNum(requireApply2.getBatchNum());
			requirementBatch.setStatus("02");// 需求状态 01 申请 02 受理 03 开发 04 测试
			requirementBatch.setDealUser(applyUser);
			requirementBatch.setUpdateTime(applyDate);

			requirementBatchMapper.updateByPrimaryKeySelective(requirementBatch);
			// 添加需求批次时间表 REQUIREMENT_BATCH_TIEM
			RequirementBatchTiem requirementBatchTiem = new RequirementBatchTiem();
			requirementBatchTiem.setQmsNo(requireApply2.getQmsNo());
			requirementBatchTiem.setBatchNum(requireApply2.getBatchNum());
			requirementBatchTiem.setApplyId(requireApply2.getId());
			requirementBatchTiem.setStatus("02");// 需求状态 01 申请 02 受理 03 开发 04 测试
			requirementBatchTiem.setUpdateTime(applyDate);
			requirementBatchTiem.setDealUser(applyUser);
			requirementBatchTiemMapper.insertSelective(requirementBatchTiem);
		}

		/*
		 * task =
		 * taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).
		 * singleResult(); // task.ca List<IdentityLink> identityLinks =
		 * taskService.getIdentityLinksForTask(task.getId()); for (IdentityLink
		 * identityLink : identityLinks) { String UserId = identityLink.getUserId();
		 * logger.info("用户Id" + UserId); }
		 */
		/*
		 * new Thread(new Runnable() {
		 * 
		 * @Override public void run() { try {
		 * taskServer.SendMessage(task.getProcessInstanceId()); } catch (IOException e)
		 * { e.printStackTrace(); } } }).start();
		 */

		return responseMessage;
	}

	/**
	 * 获取转派信息
	 * 
	 * @param taskId
	 * @return
	 */
	@RequestMapping("/getTaskReassignment")
	public ResponseMessage<Map> getTaskReassignment(@RequestParam String taskId) {
		ResponseMessage<Map> responseMessage = new ResponseMessage<Map>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功");

		Task task = taskService.createTaskQuery().includeProcessVariables().taskId(taskId).singleResult();

		Map formData = new HashMap();

		formData.put("developmentUserId", task.getProcessVariables().get("developmentUserId"));// 申请人
		formData.put("newDevelopmentUserId", task.getProcessVariables().get("newDevelopmentUserId"));// 开发人员
		formData.put("resultMessage", task.getProcessVariables().get("resultMessage"));

		responseMessage.setExtend(formData);
		logger.info(responseMessage.getMessage());
		return responseMessage;
	}

	/**
	 * 转派审批
	 * 
	 * @return
	 */
	@RequestMapping("/reassignment")
	public ResponseMessage<?> reassignmentExamine(@RequestBody Examine examine) {
		ResponseMessage<?> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("转派成功");

		Task task = taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		if ("6".equals(examine.getStatus())) {// 6审批通过
			Map formData = new HashMap();
			formData.put("developmentUserId", task.getProcessVariables().get("newDevelopmentUserId"));
			Map localVar = new HashMap();
			localVar.put("status", examine.getStatus());
			localVar.put("resultMessage", examine.getResultMessage());
			taskService.setVariablesLocal(examine.getTaskId(), localVar);
			taskService.complete(examine.getTaskId(), formData);

		} else {// 7审批拒绝
			Map formData = new HashMap();

			Map localVar = new HashMap();
			localVar.put("status", examine.getStatus());
			localVar.put("resultMessage", examine.getResultMessage());

			taskService.setVariablesLocal(examine.getTaskId(), localVar);

			taskService.complete(examine.getTaskId());

		}

		// formService.submitTaskFormData(taskId, formData);

		/*
		 * ProcessInstance instance = runtimeService.createProcessInstanceQuery()
		 * .processInstanceId(task.getProcessInstanceId()).singleResult();
		 */

		// 变更工单状态
		RequireApply requireApply = new RequireApply();

		requireApply.setId(examine.getApplyId());
		requireApply.setStatus(examine.getStatus());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					taskServer.SendMessage(task.getProcessInstanceId());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();

		/*
		 * task =
		 * taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).
		 * singleResult(); // task.ca List<IdentityLink> identityLinks =
		 * taskService.getIdentityLinksForTask(task.getId()); for (IdentityLink
		 * identityLink : identityLinks) { String UserId = identityLink.getUserId();
		 * logger.info("用户Id" + UserId); }
		 */

		return responseMessage;
	}

	/**
	 * 查询待审批流程
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	public String query(@RequestParam String instanceId) {
		Task task = taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
		return "任务编号" + task.getId();
	}

	/**
	 * 我的任务
	 * 
	 * @return
	 */
	@RequestMapping("/myTask")
	public ResponseMessage<PageInfo<SmpUser>> query1(@RequestBody PageRequest pageRequest) {
		ResponseMessage<PageInfo<SmpUser>> responseMessage = new ResponseMessage<PageInfo<SmpUser>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");

		String applyUser = request.getHeader("userName");

		long count = taskService.createTaskQuery().taskCandidateOrAssigned(applyUser).count();

		List<Task> tasks = taskService.createTaskQuery().taskCandidateOrAssigned(applyUser).includeProcessVariables()
				.orderByTaskCreateTime().desc()
				.listPage((pageRequest.getPageNum() - 1) * pageRequest.getPageSize(), pageRequest.getPageSize());
		List list = new ArrayList();
		for (Task task : tasks) {
			// taskService.cre
			// ProcessInstance instance =
			// runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();

			Map map = new HashMap();

			map.put("processInstanceId", task.getProcessInstanceId());
			map.put("taskName", task.getName());
			map.put("taskkey", task.getTaskDefinitionKey());
			map.put("taskId", task.getId());
			map.put("duUserId", task.getAssignee());
			map.put("createDate", task.getCreateTime());
			map.put("applyUser", task.getProcessVariables().get("applyUser"));
			map.put("applyDate", task.getProcessVariables().get("applyDate"));
			map.put("qmsNo", task.getProcessVariables().get("qmsNo"));
			map.put("qmsName", task.getProcessVariables().get("qmsName"));
			map.put("sid", task.getProcessVariables().get("sid"));
			map.put("applyType", task.getProcessVariables().get("applyType"));
			map.put("assignee", task.getAssignee());
			map.put("adminUsers", task.getProcessVariables().get("adminUsers"));

			if ("EnvAdminExamine".equals(task.getTaskDefinitionKey())) {
				map.put("adminUsers", task.getProcessVariables().get("testUsers"));
			} else if ("AcceptDemand".equals(task.getTaskDefinitionKey())) {
				map.put("adminUsers", task.getProcessVariables().get("developUsers"));
			}
			

			// instance.getStartTime();
			list.add(map);
		}

		PageInfo<SmpUser> pageInfo = new PageInfo<SmpUser>(list, pageRequest.getPageSize());
		pageInfo.setTotal(count);
		pageInfo.setList(list);
		responseMessage.setExtend(pageInfo);
		return responseMessage;
	}

	/**
	 * 我的任务
	 * 
	 * @return
	 */
	@RequestMapping("/myTaskCount")
	public ResponseMessage<Long> myTaskCount() {
		ResponseMessage<Long> responseMessage = new ResponseMessage<Long>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");

		String applyUser = request.getHeader("userName");

		// long count = taskService.createTaskQuery().taskAssignee(applyUser).count();
		long count = taskService.createTaskQuery().taskCandidateOrAssigned(applyUser).count();

		responseMessage.setExtend(count);
		return responseMessage;
	}

	/**
	 * 查询历史
	 * 
	 * @return
	 */
	@RequestMapping("/queryhis")
	public ResponseMessage<List<Map<?, ?>>> queryhis(@RequestBody Examine examine) {

		ResponseMessage<List<Map<?, ?>>> responseMessage = new ResponseMessage<List<Map<?, ?>>>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");

		List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery().includeTaskLocalVariables()
				.includeProcessVariables().processInstanceId(examine.getProcessInstanceId())
				.orderByHistoricTaskInstanceStartTime().asc().list();

		// logger.info("historicTaskInstance = {}",
		// ToStringBuilder.reflectionToString(tasks, ToStringStyle.JSON_STYLE));
		List list = new ArrayList();
		for (HistoricTaskInstance task : tasks) {
			logger.info("historicTaskInstance = {}",
					ToStringBuilder.reflectionToString(task, ToStringStyle.JSON_STYLE));

			Map map = new HashMap();
			map.put("Id", task.getId());
			map.put("name", task.getName());
			map.put("assignee", task.getAssignee());
			map.put("adminUsers", task.getProcessVariables().get("adminUsers"));

			if ("EnvAdminExamine".equals(task.getTaskDefinitionKey())) {
				map.put("adminUsers", task.getProcessVariables().get("testUsers"));
			} else if ("AcceptDemand".equals(task.getTaskDefinitionKey())) {
				map.put("adminUsers", task.getProcessVariables().get("developUsers"));
			}
			// map.put("category", task.);
			map.put("resultMessage", task.getTaskLocalVariables().get("resultMessage"));
			map.put("status", task.getTaskLocalVariables().get("status"));
			map.put("startTime", task.getStartTime());
			map.put("endTime", task.getEndTime());
			/*
			 * logger.info("name:" + task.getName()); logger.info("id" + task.getId());
			 */

			/*
			 * List<HistoricDetail> details =
			 * historyService.createHistoricDetailQuery().taskId(task.getId()).list(); for
			 * (HistoricDetail historicDetail : details) { //
			 * 所以需要将HistoricDetail转换为HistoricVariableUpdate才可以获取到variables
			 * HistoricFormPropertyEntityImpl historicVariableUpdate =
			 * (HistoricFormPropertyEntityImpl) historicDetail;
			 * 
			 * logger.info(historicVariableUpdate.toString());
			 * 
			 * logger.info(historicVariableUpdate.getPropertyId());
			 * logger.info(historicVariableUpdate.getPropertyValue()); historicDetail.get }
			 */

			// TaskFormData taskFormData = formService.getTaskFormData(task.getId());
			// logger.info("===");
			/*
			 * List<FormProperty> taskFormDataFormProperties =
			 * taskFormData.getFormProperties(); for (FormProperty property
			 * :taskFormDataFormProperties) { //
			 * LOGGER.info("property = {}",ToStringBuilder.reflectionToString(property,
			 * ToStringStyle.JSON_STYLE)); System.out.println(property.getName());
			 * System.out.println(property.getValue()); }
			 */
			list.add(map);
		}
		responseMessage.setExtend(list);
		return responseMessage;
	}

	static String toString(HistoricDetail historicDetail) {
		return ToStringBuilder.reflectionToString(historicDetail, ToStringStyle.SHORT_PREFIX_STYLE); // 返回SHORT_PREFIX_STYLE格式
	}

	@RequestMapping("/view")
	public void bpmnView(HttpServletRequest request, HttpServletResponse response, @RequestBody Examine examine) {
		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// Task task =
		// taskService.createTaskQuery().taskId(examine.getTaskId()).singleResult();

		try {

			// 获取历史流程实例
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
					.processInstanceId(examine.getProcessInstanceId()).singleResult();
			// 获取流程中已经执行的节点，按照执行先后顺序排序
			List<HistoricActivityInstance> historicActivityInstances = historyService
					.createHistoricActivityInstanceQuery().processInstanceId(examine.getProcessInstanceId())
					.orderByHistoricActivityInstanceId().asc().list();
			// 高亮已经执行流程节点ID集合
			List<String> highLightedActivitiIds = new ArrayList<>();
			/*
			 * for (HistoricActivityInstance historicActivityInstance :
			 * historicActivityInstances) {
			 * highLightedActivitiIds.add(historicActivityInstance.getActivityId()); }
			 */

			// 获取下一步需要执行的节点

			Task task = taskService.createTaskQuery().processInstanceId(examine.getProcessInstanceId()).singleResult();

			List<String> hightLightElements = new ArrayList<>();
			if (task != null) {
				hightLightElements.add(task.getTaskDefinitionKey());
			}

			List<HistoricProcessInstance> historicFinishedProcessInstances = historyService
					.createHistoricProcessInstanceQuery().processInstanceId(request.getParameter("instanceId"))
					.finished().list();
			ProcessDiagramGenerator processDiagramGenerator = null;
			// 如果还没完成，流程图高亮颜色为绿色，如果已经完成为红色

			/*
			 * if (!CollectionUtils.isEmpty(historicFinishedProcessInstances)) { //
			 * 如果不为空，说明已经完成
			 */
			processDiagramGenerator = engineConfiguration.getProcessDiagramGenerator();

			BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
			// 高亮流程已发生流转的线id集合
			/*
			 * List<String> highLightedFlowIds = getHighLightedFlows(bpmnModel,
			 * historicActivityInstances);
			 */
			List<String> highLightedFlowIds = new ArrayList();
			// 使用默认配置获得流程图表生成器，并生成追踪图片字符流

			InputStream imageStream = processDiagramGenerator.generateDiagram(bpmnModel, "png", hightLightElements,
					highLightedFlowIds, "宋体", "微软雅黑", "黑体", null, 2.0);

			// 输出图片内容
			byte[] b = new byte[1024];
			int len;
			while ((len = imageStream.read(b, 0, 1024)) != -1) {
				outputStream.write(b, 0, len);
			}
		} catch (Exception e) {
			logger.error("processInstanceId" + "生成流程图失败，原因：" + e.getMessage(), e);
		}

	}

	@RequestMapping("/view1")
	public ResponseMessage<Map> bpmnView1(@RequestBody Examine examine) {
		ResponseMessage<Map> responseMessage = new ResponseMessage<>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功");
		Map result = new HashMap();

		try {

			// 获取历史流程实例
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
					.processInstanceId(examine.getProcessInstanceId()).singleResult();
			// 获取流程中已经执行的节点，按照执行先后顺序排序
			List<HistoricActivityInstance> historicActivityInstances = historyService
					.createHistoricActivityInstanceQuery().processInstanceId(examine.getProcessInstanceId())
					.orderByHistoricActivityInstanceId().asc().list();
			// 高亮已经执行流程节点ID集合
			List<String> highLightedActivitiIds = new ArrayList<>();

			for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
				highLightedActivitiIds.add(historicActivityInstance.getActivityId());
			}

			result.put("highLightedActivitiIds", highLightedActivitiIds);
			// 获取下一步需要执行的节点

			Task task = taskService.createTaskQuery().processInstanceId(examine.getProcessInstanceId()).singleResult();

			List<String> hightLightElements = new ArrayList<>();
			if (task != null) {
				hightLightElements.add(task.getTaskDefinitionKey());
			}
			result.put("hightLightElements", hightLightElements);
			List<HistoricProcessInstance> historicFinishedProcessInstances = historyService
					.createHistoricProcessInstanceQuery().processInstanceId(request.getParameter("instanceId"))
					.finished().list();
			ProcessDiagramGenerator processDiagramGenerator = null;
			// 如果还没完成，流程图高亮颜色为绿色，如果已经完成为红色

			/*
			 * if (!CollectionUtils.isEmpty(historicFinishedProcessInstances)) { //
			 * 如果不为空，说明已经完成
			 */
			processDiagramGenerator = engineConfiguration.getProcessDiagramGenerator();

			BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
			// 高亮流程已发生流转的线id集合

			List<String> highLightedFlowIds = getHighLightedFlows(bpmnModel, historicActivityInstances);
			result.put("highLightedFlowIds", highLightedFlowIds);
			// List<String> highLightedFlowIds = new ArrayList();
			// 使用默认配置获得流程图表生成器，并生成追踪图片字符流

			/*
			 * InputStream imageStream = processDiagramGenerator.generateDiagram(bpmnModel,
			 * "png", hightLightElements, highLightedFlowIds, "宋体", "微软雅黑", "黑体", null,
			 * 2.0);
			 * 
			 * // 输出图片内容 byte[] b = new byte[1024]; int len; while ((len =
			 * imageStream.read(b, 0, 1024)) != -1) { outputStream.write(b, 0, len); }
			 */
		} catch (Exception e) {
			logger.error("processInstanceId" + "生成流程图失败，原因：" + e.getMessage(), e);
		}
		responseMessage.setExtend(result);
		return responseMessage;

	}

	/**
	 * 获取已经流转的线
	 * 
	 * @param bpmnModel
	 * @param historicActivityInstances
	 * @return
	 */
	private static List<String> getHighLightedFlows(BpmnModel bpmnModel,
			List<HistoricActivityInstance> historicActivityInstances) {
		// 高亮流程已发生流转的线id集合
		List<String> highLightedFlowIds = new ArrayList<>();
		// 全部活动节点
		List<FlowNode> historicActivityNodes = new ArrayList<>();
		// 已完成的历史活动节点
		List<HistoricActivityInstance> finishedActivityInstances = new ArrayList<>();

		for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
			FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess()
					.getFlowElement(historicActivityInstance.getActivityId(), true);
			historicActivityNodes.add(flowNode);
			if (historicActivityInstance.getEndTime() != null) {
				finishedActivityInstances.add(historicActivityInstance);
			}
		}

		FlowNode currentFlowNode = null;
		FlowNode targetFlowNode = null;
		// 遍历已完成的活动实例，从每个实例的outgoingFlows中找到已执行的
		for (HistoricActivityInstance currentActivityInstance : finishedActivityInstances) {
			// 获得当前活动对应的节点信息及outgoingFlows信息
			currentFlowNode = (FlowNode) bpmnModel.getMainProcess()
					.getFlowElement(currentActivityInstance.getActivityId(), true);
			List<SequenceFlow> sequenceFlows = currentFlowNode.getOutgoingFlows();

			/**
			 * 遍历outgoingFlows并找到已已流转的 满足如下条件认为已已流转：
			 * 1.当前节点是并行网关或兼容网关，则通过outgoingFlows能够在历史活动中找到的全部节点均为已流转
			 * 2.当前节点是以上两种类型之外的，通过outgoingFlows查找到的时间最早的流转节点视为有效流转
			 */
			if ("parallelGateway".equals(currentActivityInstance.getActivityType())
					|| "inclusiveGateway".equals(currentActivityInstance.getActivityType())) {
				// 遍历历史活动节点，找到匹配流程目标节点的
				for (SequenceFlow sequenceFlow : sequenceFlows) {
					targetFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(sequenceFlow.getTargetRef(),
							true);
					if (historicActivityNodes.contains(targetFlowNode)) {
						highLightedFlowIds.add(targetFlowNode.getId());
					}
				}
			} else {
				List<Map<String, Object>> tempMapList = new ArrayList<>();
				for (SequenceFlow sequenceFlow : sequenceFlows) {
					for (HistoricActivityInstance historicActivityInstance : historicActivityInstances) {
						if (historicActivityInstance.getActivityId().equals(sequenceFlow.getTargetRef())) {
							Map<String, Object> map = new HashMap<>();
							map.put("highLightedFlowId", sequenceFlow.getId());
							map.put("highLightedFlowStartTime", historicActivityInstance.getStartTime().getTime());
							tempMapList.add(map);
						}
					}
				}

				if (!CollectionUtils.isEmpty(tempMapList)) {
					// 遍历匹配的集合，取得开始时间最早的一个
					long earliestStamp = 0L;
					String highLightedFlowId = null;
					for (Map<String, Object> map : tempMapList) {
						long highLightedFlowStartTime = Long.valueOf(map.get("highLightedFlowStartTime").toString());
						if (earliestStamp == 0 || earliestStamp >= highLightedFlowStartTime) {
							highLightedFlowId = map.get("highLightedFlowId").toString();
							earliestStamp = highLightedFlowStartTime;
						}
					}

					highLightedFlowIds.add(highLightedFlowId);
				}

			}

		}
		return highLightedFlowIds;
	}

}
